﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web.Script.Serialization;



namespace ABDLight
{
    public partial class frmLogin : Form
    {
        bool StgOpenFlag = false;
        //public static readonly ILog log = LogManager.GetLogger(typeof(frmLogin));



        public frmLogin()
        {
            //log.Info("== Инициализация формы frmLogin ==");
            InitializeComponent();

            BtnChangeLoc(-1);
        }

        public static System.String SHA512(string NotHashedPass)
        {
            System.String Hashed = "0x" + System.BitConverter.ToString(((System.Security.Cryptography.SHA512)new System.Security.Cryptography.SHA512Managed()).ComputeHash(System.Text.Encoding.ASCII.GetBytes(NotHashedPass))).Replace("-", "");

            return Hashed;
        }



        // String e_mail = "name@gmail.";

        public bool isValidMail(string e_mail = "")
        {
            string pattern = "[.\\-_a-z0-9]+@([a-z0-9][\\-a-z0-9]+\\.)+[a-z]{2,6}";
            string input = e_mail;

            bool isMatch = false;
            string status = " не E-Mail!";

            foreach (Match field in Regex.Matches(input, pattern))
            {
                isMatch = true;
                status = " E-Mail!";
            }

            Console.WriteLine("{0},{1}", isMatch.ToString().ToLower(), input + status);
            return isMatch;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {

            if (!TestConnection())
            {
                this.DialogResult = DialogResult.Retry;
                return;
            }

            ((frmMine)this.Owner).cfg.Login = edLogin.Text;
            ((frmMine)this.Owner).cfg.Pwd = edPass.Text;
            ((frmMine)this.Owner).cfg.edPass = edPass.Text;

            ((frmMine)this.Owner).cfg.Http = edServ.Text;



            ABDLight.Properties.Settings.Default.Login = ((frmMine)this.Owner).cfg.Login.ToString();
            ABDLight.Properties.Settings.Default.edPwd = ((frmMine)this.Owner).cfg.edPass.ToString();
            ABDLight.Properties.Settings.Default.Pwd = SHA512(((frmMine)this.Owner).cfg.Pwd);

            ABDLight.Properties.Settings.Default.Http = ((frmMine)this.Owner).cfg.Http.ToString();

            ABDLight.Properties.Settings.Default.CheckEmail = edServ.Text + "/Services/IQDQ/CheckEmail?email=";
            ABDLight.Properties.Settings.Default.CheckFIO = edServ.Text + "/Services/IQDQ/CheckFIO?phrase=";
            ABDLight.Properties.Settings.Default.CheckPhone = edServ.Text + "/Services/IQDQ/CheckPhone?phone=phone_value&KLADR=KLADR_value";
            ABDLight.Properties.Settings.Default.SelectAddr_Url = edServ.Text + "/Services/IQDQ/SelectAddress?addr=";
            ABDLight.Properties.Settings.Default.SearchAddr_Url = edServ.Text + "/Services/IQDQ/SearchAddressDetail?addr=";


            ABDLight.Properties.Settings.Default.Save();

            this.DialogResult = DialogResult.OK;
            this.Close();

            //log.Info("User \"" + ABDLight.Properties.Settings.Default.UserID + "\" - try to LogIn!");

        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            edLogin.Text = ABDLight.Properties.Settings.Default.Login;
            edPass.Text = ABDLight.Properties.Settings.Default.edPwd;
            edServ.Text = ABDLight.Properties.Settings.Default.Http;
        }


        private void BtnChangeLoc(int dir)
        {
            int S = 50;

            btnOk.Location = new Point(btnOk.Location.X, btnOk.Location.Y + dir * S);
            btnCancel.Location = new Point(btnCancel.Location.X, btnCancel.Location.Y + dir * S);
            btnSet.Location = new Point(btnSet.Location.X, btnSet.Location.Y + dir * S);
        }

        public bool TestConnection()
        {
            //string TestConn = edServ.Text + "/services/IQDQ/CheckEmail?email=test@test.ru&login=" + HttpUtility.UrlEncode(edLogin.Text) + "&pwd=" + HttpUtility.UrlEncode(edPass.Text);
            string TestConn = edServ.Text + "/account/ServicePermission?logIn=" + HttpUtility.UrlEncode(edLogin.Text) + "&paSs=" + HttpUtility.UrlEncode(edPass.Text);

            try
            {
                string responsetext;
                try
                {
                    responsetext = new StreamReader(HttpWebRequest.Create(TestConn).GetResponse().GetResponseStream()).ReadToEnd();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(this, "Ошибка подключения!\nПроверьте подключение к сети и доступ к сервисам IQDQ!\nПри повторной ошибке обратитесь к администратору сети!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                Dictionary<string, string> res = JSONObject.ParseAllJSON(responsetext);

                string c_status_desc = "";
                //ServError Serv = new JavaScriptSerializer().Deserialize<ServError>(responsetext);
                foreach (KeyValuePair<string, string> item in res)
                {
                    c_status_desc = (item.Key.IndexOf("c_status_desc") >= 0) ? item.Value : "";
                }
                if (responsetext.ToLower() != "ok" && c_status_desc.ToLower() != "ок")
                {
                    MessageBox.Show(this, "Ошибка подключения:\n" + responsetext + "\nОбратитесь к администратору сети!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch { }

            return true;
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            if (!StgOpenFlag)
            {
                edServ.Visible = true;
                label6.Visible = true;
                btnCheck.Visible = true;

                BtnChangeLoc(1);
                btnSet.Text = "Скрыть настройки";

                StgOpenFlag = true;
            }
            else
            {
                edServ.Visible = false;
                label6.Visible = false;
                btnCheck.Visible = false;

                BtnChangeLoc(-1);
                btnSet.Text = "Расширенные настройки";

                StgOpenFlag = false;
            }

        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (TestConnection()) MessageBox.Show(this, "Тестовое подключение завершилось удачно", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnViewPass_Click(object sender, EventArgs e)
        {
            if (edPass.PasswordChar == '*')
                edPass.PasswordChar = '\0';
            else
                edPass.PasswordChar = '*';

        }

        private void frmLogin_Closing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.Retry)
                e.Cancel = true;
        }

    }

    public class ServError
    {
        public string error { get; set; }
        public string msg { get; set; }

    }
}
